package fpt.edu.vn.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.hsqldb.lib.StringUtil;

import fpt.edu.vn.model.Districts;
import fpt.edu.vn.model.Favorites;
import fpt.edu.vn.model.Locationtypes;
import fpt.edu.vn.model.Provinces;
import fpt.edu.vn.model.Ratetopics;
import fpt.edu.vn.model.Reportspams;
import fpt.edu.vn.model.Topicimages;
import fpt.edu.vn.model.Topics;
import fpt.edu.vn.model.Users;
import fpt.edu.vn.util.HibernateUtil;

/* 
 * TopicsDao.java
 *  
 * 0.1
 * 
 * 10/15/2012 
 *  
 * Copyright notice 
 *  
 * Modification Logs: 
 *   DATE        AUTHOR      DESCRIPTION 
 *  -------------------------------------------------------- 
 *  15-Oct-2012  ThuongND    Create new 
 */
public class AddnewDao {

	public Topics add(Topics topic) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(topic);
		session.getTransaction().commit();
		return topic;
	}

	// update img topic
	// update topic
	public boolean updateImg(int topicId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Topics tptemp = (Topics) session.load(Topics.class, topicId);
		tptemp.setImage("icon-chothue.png");
		session.update(tptemp);
		session.getTransaction().commit();
		return true;
	}

	// update topic
	public Topics update(Topics topic) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Topics tptemp = (Topics) session.load(Topics.class, topic.getTopicId());
		//tptemp.setUsersId(topic.getUsersId());
		tptemp.setTitle(topic.getTitle());
		// tptemp post = 1 or share =2
		tptemp.setTopicTypeId(topic.getTopicTypeId());
		tptemp.setStatusTopicId(topic.getStatusTopicId());
		tptemp.setEditDate(topic.getEditDate());
		tptemp.setDistrictId(topic.getDistrictId());
		tptemp.setAddress(topic.getAddress());
		tptemp.setPrice(topic.getPrice());
		tptemp.setArea(topic.getArea());
		tptemp.setContact(topic.getContact());
		tptemp.setPhone(topic.getPhone());
		tptemp.setDescription(topic.getDescription());
		// set Latitude
		tptemp.setLatitude(topic.getLatitude());
		// set Longitude
		tptemp.setLongitude(topic.getLongitude());
		// view num set =0
		//tptemp.setViewNum(topic.getViewNum());
		if (topic.getImage() != null) {
			tptemp.setImage(topic.getImage());
		}
		tptemp.setCook(topic.getCook());
		tptemp.setOwner(topic.getOwner());
		tptemp.setWater(topic.getWater());
		tptemp.setPower(topic.getPower());
		tptemp.setToilet(topic.getToilet());
		tptemp.setInternet(topic.getInternet());
		tptemp.setHouseType(topic.getHouseType());
		tptemp.setHour(topic.getHour());
		tptemp.setMotor(topic.getMotor());
		tptemp.setMotorPrice(topic.getMotorPrice());
		session.update(tptemp);
		session.getTransaction().commit();
		return topic;
	}
		
	//out spam topic
			public boolean outspam(String[] topicIds) {
				Session session = HibernateUtil.getSessionFactory().getCurrentSession();
				session.beginTransaction();
				boolean delete = false;
				try {
					for(String topicId: topicIds){
						String hql = "delete from Reportspams where topicId =" + Integer.parseInt(topicId);
						Query query = session.createQuery(hql);
						query.executeUpdate();
					}
					
					

				} catch (HibernateException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				session.getTransaction().commit();
				return delete;
			}
		//hide multi topic
		public boolean hideMulti(String[] topicIds) {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			for(String topicId:topicIds){
				Topics tptemp = (Topics) session.load(Topics.class,Integer.parseInt(topicId));
				//hide topic
				tptemp.setStatusTopicId(2);
				session.update(tptemp);
				
			}
			
			session.getTransaction().commit();
			return true;
		}
		//show multi topic
				public boolean showMulti(String[] topicIds) {
					Session session = HibernateUtil.getSessionFactory().getCurrentSession();
					session.beginTransaction();
					for(String topicId:topicIds){
						Topics tptemp = (Topics) session.load(Topics.class,Integer.parseInt(topicId));
						//hide topic
						tptemp.setStatusTopicId(1);
						session.update(tptemp);
						
					}
					
					session.getTransaction().commit();
					return true;
				}
				
	public Topicimages add(Topicimages topicimages) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(topicimages);
		session.getTransaction().commit();
		return topicimages;
	}

	public Favorites addFavorite(Favorites fav) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(fav);
		session.getTransaction().commit();
		return fav;
	}

	public Ratetopics addRate(Ratetopics rate) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(rate);
		session.getTransaction().commit();
		return rate;
	}

	public Reportspams reportSpam(Reportspams spam) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(spam);
		session.getTransaction().commit();
		return spam;
	}

	// get topicid vua tao
	@SuppressWarnings("unchecked")
	public List<Topics> topicexist(int usersId, String title, String address,
			String description) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Topics> topics = null;
		try {
			StringBuffer hsql = new StringBuffer();
			hsql.append("FROM Topics ");
			hsql.append("WHERE 1 = 1 ");
			hsql.append("AND LOWER(usersId) = :usersId ");
			hsql.append("AND LOWER(title) LIKE :title ");
			hsql.append("AND LOWER(address) LIKE :address ");
			hsql.append("AND LOWER(description) LIKE :description ");
			hsql.append(" Order by createDate desc");

			Query query = session.createQuery(hsql.toString());

			query.setParameter("usersId", usersId);
			if (!StringUtil.isEmpty(title)) {
				query.setParameter("title", title);
			}
			if (!StringUtil.isEmpty(address)) {
				query.setParameter("address", address);
			}
			if (!StringUtil.isEmpty(description)) {
				query.setParameter("description", description);
			}

			topics = query.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return topics;
	}

	// -end get topic--

	@SuppressWarnings("unchecked")
	public List<Object> list() {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Object> topics = null;
		try {

			topics = (List<Object>) session
					.createQuery(
							"select t.title, t.address, t.price, t.viewNum, t.latitude, t.longitude, t.image, t.topicId, t.description, t.topicTypeId , t.districtId from Topics t where t.statusTopicId = 1 order by t.editDate desc")
					.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return topics;
	}

	// get userID
	@SuppressWarnings("unchecked")
	public List<Users> getUser_Id(String email) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Users> user = null;
		try {
			user = session.createQuery(
					"from Users u where u.email =  '" + email + "'").list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		session.getTransaction().commit();
		return user;
	}

	// login admin check
	@SuppressWarnings("unchecked")
	public List<Users> getAdminlogin(String email, String password) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Users> user = null;
		try {
			if (!StringUtil.isEmpty(email) && !StringUtil.isEmpty(password)) {
				StringBuffer hsql = new StringBuffer();
				hsql.append("FROM Users ");
				hsql.append("WHERE 1 = 1 ");
				hsql.append("AND LOWER(email) = :email ");
				hsql.append("AND LOWER(password) = :password ");

				Query query = session.createQuery(hsql.toString());
				query.setParameter("email", email);

				query.setParameter("password", password);

				user = query.list();
			}

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return user;
	}

	// end login admin check
	// get province
	@SuppressWarnings("unchecked")
	public List<Provinces> getProvince() {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Provinces> provinces = null;
		try {

			provinces = (List<Provinces>) session.createQuery(
					"from Provinces p").list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return provinces;
	}
	// get location type
		@SuppressWarnings("unchecked")
		public List<Locationtypes> getLocationtypes() {

			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			List<Locationtypes> locationtypes = null;
			try {

				locationtypes = (List<Locationtypes>) session.createQuery(
						"from Locationtypes p").list();

			} catch (HibernateException e) {
				e.printStackTrace();
			}
			return locationtypes;
		}
	// get districts
	@SuppressWarnings("unchecked")
	public List<Districts> getDistricts(int provinceId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Districts> districts = null;
		try {
			// String sql =
			// "from Districts d where d.provinceId = :province_Id ";
			// Query query = session.createQuery(sql);
			// query.setParameter("province_Id", temp);
			// districts = (List<Districts>)query.list();

			districts = (List<Districts>) session.createQuery(
					"from Districts d where d.provinceId = " + provinceId)
					.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return districts;
	}

	// get province
	@SuppressWarnings("unchecked")
	public List<Districts> getProvinceInfo(int districtId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Districts> districts = null;
		try {
			StringBuffer hsql = new StringBuffer();
			hsql.append("FROM Districts ");
			hsql.append("WHERE 1 = 1 ");
			hsql.append("AND LOWER(districtId) = :districtId ");

			Query query = session.createQuery(hsql.toString());

			query.setParameter("districtId", districtId);

			districts = query.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return districts;
	}

	// check favorite
	public boolean checkAddFavorite(int usersId, int topicId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		boolean exits = true;
		String hql = "select usersId from Favorites where usersId = " + usersId
				+ " and topicId = " + topicId;
		Query query = session.createQuery(hql);
		int rowCount = query.list().size();
		if (rowCount == 0) {
			exits = false;
		} else {
			exits = true;
		}
		session.getTransaction().commit();
		return exits;
	}

	// check Ratetopics
	public boolean checkRatetopics(int usersId, int topicId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		boolean exits = true;
		String hql = "select usersId from Ratetopics where usersId = "
				+ usersId + " and topicId = " + topicId;
		Query query = session.createQuery(hql);
		int rowCount = query.list().size();
		if (rowCount == 0) {
			exits = false;
		} else {
			exits = true;
		}
		session.getTransaction().commit();
		return exits;
	}

	// update rate
	public boolean updateRate(int usersId, int topicId, int point) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		boolean update = false;
		try {
			String hql = "update Ratetopics set pointRate = " + point
					+ "  where usersId =" + usersId + " and topicId = "
					+ topicId;
			Query query = session.createQuery(hql);
			int rowCount = query.executeUpdate();
			if (rowCount < 1) {
			} else {
				update = true;
			}

		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		session.getTransaction().commit();
		return update;
	}

	// Compare
	@SuppressWarnings("unchecked")
	public List<Object> detailToCompare(int topicId) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Object> topicdetail = null;
		try {

			topicdetail = (List<Object>) session
					.createQuery(
							"select t.title, t.address, t.area, t.price, t.contact, t.phone, t.viewNum, t.description, t.createDate , t.editDate , t.renewDate, t.latitude, t.longitude, t.image, t.topicId, t.topicTypeId, t.water, t.power, t.toilet, t.cook, t.internet, t.houseType, t.motor, t.motorPrice, t.hour, t.owner, t.districtId from Topics t where  t.topicId = "
									+ topicId).list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return topicdetail;
	}

}
